<template>
  <div class="subject-manage">
    <el-row :gutter="4" type="flex" justify="start">
      <el-col :span="24">
        <el-cascader
          :change-on-select="true"
          :options="courseCategorys"
          v-model="selectedOptions"
          @change="handleChange"
        />
        <el-select v-model="status" @change="handleChange">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input v-model="courseTitle" placeholder="课程名称" style="width:200px;" @keyup.enter.native="handleChange"/>
        <el-input v-model="userName" placeholder="创建者" style="width:200px;" @keyup.enter.native="handleChange"/>
        <el-button type="primary" @click="handleChange">搜索</el-button>
        <el-button size="medium" type="info" @click="clearParams">清空</el-button>
      </el-col>
    </el-row>
    <ul class="tablecheck">
      <li>
        课程 :
        <span>{{ tableList.classroom }}</span> 个
      </li>
      <li>
        已发布 :
        <span>{{ tableList.published }}</span> 个
      </li>
      <li>
        已关闭 :
        <span>{{ tableList.closed }}</span> 个
      </li>
      <li>
        未发布 :
        <span>{{ tableList.unpublish }}</span> 个
      </li>
    </ul>
    <eltable
      :table-label="tableLabel"
      :table-data="tableData.slice((currentpage-1)*pagesize,currentpage*pagesize)"
    >
      <el-table-column slot="first" label="编号" align="center" min-width="5">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column slot="second" label="名称" align="center" min-width="20">
        <template slot-scope="scope">
          <el-button type="text">{{ scope.row.title }}</el-button>
          <br>
          <span style="color:#8a8aa;font-size:12px;">分类: {{ scope.row.categoryName }}</span>
        </template>
      </el-table-column>
      <el-table-column slot="isPro" label="创建者/时间" align="center" min-width="20">
        <template slot-scope="scope">
          <el-button type="text" @click="handleClickDialog(scope)">{{ scope.row.userName }}</el-button>
          <br>
          <span style="color:#8a8aa;font-size:12px;">{{ scope.row.createTimeStr }}</span>
        </template>
      </el-table-column>
      <el-table-column slot="button" label="操作" prop="manage" align="center" min-width="20">
        <template slot-scope="scope">
          <el-dropdown trigger="click" @command="handleClick($event, scope)">
            <el-button type="primary">
              管理
              <i class="el-icon-arrow-down el-icon--right"/>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="1">预览课程</el-dropdown-item>
              <el-dropdown-item command="2">删除课程</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.status === 'published'" command="3">关闭课程</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.status === 'draft' || scope.row.status === 'closed'" command="4">发布课程</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </eltable>
    <pagination
      :total="total"
      :current-page="currentpage"
      :page-size="pagesize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <user-dialog
      :visiabledialog="userdialog"
      :dialog-data="dialogData"
      @changeVisiable="userdialog = false"
    />
  </div>
</template>

<script>
import UserDialog from '@/components/Dialog'
import Eltable from '@/components/Eltable'
import Pagination from '@/components/Pagination'
import { getUserDetail } from '@/api/operate/userDetail' // 数据接口
import { getTenantId } from '@/utils/auth'
import { getArrangeList, deleteCourse, updateCourse } from '@/api/subject/course' // 数据接口
import { getCategoryList } from '@/api/subject/category' // 数据接口
export default {
  components: {
    Eltable,
    Pagination,
    UserDialog
  },
  data() {
    return {
      userdialog: false,
      dialogData: {},
      total: 0,
      currentpage: 1,
      pagesize: 10,
      status: '',
      courseTitle: '',
      userName: '',
      tableList: {
        published: '0',
        closed: '0',
        unpublish: '0',
        classroom: '0'
      },
      courseCategorys: [
        {
          value: '',
          label: '课程分类'
        }
      ],
      selectedOptions: [],
      statusList: [
        {
          label: '课程状态',
          value: ''
        },
        {
          label: '已发布',
          value: '已发布'
        },
        {
          label: '已关闭',
          value: '已关闭'
        },
        {
          label: '未发布',
          value: '未发布'
        }
      ],
      tableLabel: [
        {
          label: '价格',
          prop: 'price',
          width: '10'
        },
        {
          label: '课程状态',
          prop: 'statusStr',
          width: '10'
        },
        {
          label: '学员数',
          prop: 'studentNum',
          width: '10'
        }
      ],
      tableData: [],
      listFilter: []
    }
  },
  created() {
    this.getData();
    this.getCategoryList()
  },
  updated() {
    this.statusfil()
  },
  methods: {
    handleSizeChange(val) {
      console.log(val);
      this.currentpage = 1;
      this.pagesize = val.value;
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    },
    handleCurrentChange(val) {
      console.log(val);
      this.currentpage = val.value;
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    },
    // 挑选已发布 未发布 已关闭的数据 ↓
    statusfil() {
      this.tableList.published = this.tableData.filter((item) => { return item.status === 'published' }).length;
      this.tableList.closed = this.tableData.filter((item) => { return item.status === 'closed' }).length;
      this.tableList.unpublish = this.tableData.filter((item) => { return item.status === 'draft' }).length;
      this.tableList.classroom = this.tableData.length
    },
    handleClickDialog(scope) {
      getUserDetail(scope.row.userId).then(response => {
        this.dialogData = response.data.item
      });
      this.userdialog = true
    },
    handleChange() {
      this.tableData = this.listFilter.filter(item => {
        if (this.selectedOptions[0] && item.categoryName !== this.selectedOptions[this.selectedOptions.length - 1]) return false;
        if (this.status && item.statusStr !== this.status) return false;
        if (this.courseTitle && item.title.toLocaleLowerCase().indexOf(this.courseTitle.toLocaleLowerCase()) === -1) return false;
        if (this.userName && item.userName.toLocaleLowerCase().indexOf(this.userName.toLocaleLowerCase()) === -1) return false;
        return true
      });
      this.total = this.tableData.length
    },
    clearParams() {
      this.selectedOptions = '';
      this.status = '';
      this.courseTitle = '';
      this.userName = '';
      this.getData()
    },
    handleClick(command, scope) {
      if (command === '1') {
        this.$notify({
          title: '成功',
          message: '预览',
          type: 'success',
          duration: 2000
        })
      } else if (command === '2') {
        this.$confirm(`真的要删除该课程吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteCourse(scope.row.id).then(reponse => {
            if (reponse.code === 200) {
              this.$notify({
                title: '成功',
                message: '课程已被删除',
                type: 'success',
                duration: 2000
              });
              this.getData()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除'
          })
        })
      } else if (command === '3') {
        scope.row.status = 'closed';
        updateCourse(scope.row).then(res => {
          this.getData()
        })
      } else if (command === '4') {
        scope.row.status = 'published';
        updateCourse(scope.row).then(res => {
          this.getData()
        })
      }
    },
    getData() {
      getArrangeList(getTenantId()).then(res => {
        res.data.items.map(item => {
          if (item.status === 'published') item.statusStr = '已发布';
          if (item.status === 'closed') item.statusStr = '已关闭';
          if (item.status === 'draft') item.statusStr = '未发布';
          if (item.createTime) item.createTimeStr = new Date(item.createTime).toLocaleString().replace(/[\u4e00-\u9fa5]/g, '')
        });
        this.tableData = res.data.items;
        this.total = res.data.items.length;
        this.listFilter = res.data.items
      })
    },
    getCategoryList() {
      getCategoryList('course', getTenantId(),'0').then(response => {
        response.data.items.forEach(item => {
          item.label = item.name;
          item.value = item.name;
          if (item.parentId === 0) {
            item.children = [];
            this.courseCategorys.push(item)
          }
        });
        response.data.items.forEach(item => {
          if (item.parentId !== 0) {
            item.label = item.name;
            item.value = item.name;
            this.courseCategorys.forEach(category => {
              if (item.parentId === category.id) {
                category.children.push(item)
              }
            })
          }
        })
      })
    }
  }
}
</script>

<style lang="scss">
.subject-manage {
  .tablecheck {
    list-style: none;
    padding: 0 0 0 11px;
    margin: 14px 0 21px;
    height: 44px;
    line-height: 44px;
    box-sizing: border-box;
    background-color: #f8f8f8;
    li {
      float: left;
      display: block;
      margin-right: 20px;
      color: #72726f;
      span {
        color: rgb(15, 202, 62);
        font-weight: 600;
      }
    }
  }
}
</style>
